package com.cskaoyan.servlet;

import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.UserParameter;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.model.MarketUser;
import com.cskaoyan.service.UserService;
import com.cskaoyan.service.impl.UserServiceImpl;
import com.cskaoyan.utils.JacksonUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/admin/user/*")
public class AdminUserServlet extends CommonServlet {
    UserService userService = new UserServiceImpl();

    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        UserParameter userParameter = new UserParameter();
        BeanUtils.copyProperties(userParameter, parameterMap);

        PageData pageData = userService.list(userParameter);
        return BaseRespVo.ok(pageData);
    }

    public BaseRespVo detail(HttpServletRequest request, HttpServletResponse response) {
        String idStr = request.getParameter("id");
        Integer id = Integer.valueOf(idStr);

        MarketUser marketUser = userService.detail(id);
        return BaseRespVo.ok(marketUser);
    }

    public BaseRespVo update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        MarketUser marketUser = JacksonUtil.read(jsonStr, MarketUser.class);

        userService.update(marketUser);

        return BaseRespVo.ok(null);
    }
}
